// API响应基础类型
export interface ApiResponse<T = any> {
  success: boolean;
  data?: T;
  message?: string;
  error?: ApiError;
  meta?: ResponseMeta;
  timestamp: string;
  requestId: string;
}

// API错误类型
export interface ApiError {
  code: string | number;
  message: string;
  details?: string;
  field?: string;
  type:
    | "validation"
    | "authentication"
    | "authorization"
    | "not_found"
    | "conflict"
    | "rate_limit"
    | "server_error"
    | "network_error"
    | "timeout"
    | "unknown";
  stack?: string;
  metadata?: Record<string, any>;
}

// 响应元数据类型
export interface ResponseMeta {
  page?: number;
  limit?: number;
  total?: number;
  totalPages?: number;
  hasNext?: boolean;
  hasPrev?: boolean;
  processingTime?: number;
  cacheHit?: boolean;
  version?: string;
  deprecationWarning?: string;
}

// 分页请求参数类型
export interface PaginationParams {
  page?: number;
  limit?: number;
  offset?: number;
  sortBy?: string;
  sortOrder?: "asc" | "desc";
}

// 分页响应类型
export interface PaginatedResponse<T> {
  items: T[];
  pagination: {
    page: number;
    limit: number;
    total: number;
    totalPages: number;
    hasNext: boolean;
    hasPrev: boolean;
  };
}

// 搜索请求参数类型
export interface SearchParams extends PaginationParams {
  query?: string;
  filters?: Record<string, any>;
  facets?: string[];
  highlight?: boolean;
  includeMetadata?: boolean;
}

// 搜索响应类型
export interface SearchResponse<T> {
  results: Array<{
    item: T;
    score: number;
    highlights?: Record<string, string[]>;
    metadata?: Record<string, any>;
  }>;
  facets?: Record<
    string,
    Array<{
      value: string;
      count: number;
    }>
  >;
  suggestions?: string[];
  total: number;
  queryTime: number;
}

// 批量操作请求类型
export interface BulkRequest<T> {
  items: T[];
  options?: {
    continueOnError?: boolean;
    validateAll?: boolean;
    batchSize?: number;
    parallel?: boolean;
  };
}

// 批量操作响应类型
export interface BulkResponse<T> {
  successful: T[];
  failed: Array<{
    item: any;
    error: ApiError;
    index: number;
  }>;
  summary: {
    total: number;
    successful: number;
    failed: number;
    processingTime: number;
  };
}

// 文件上传响应类型
export interface UploadResponse {
  id: string;
  filename: string;
  originalName: string;
  mimeType: string;
  size: number;
  url: string;
  thumbnailUrl?: string;
  metadata?: {
    width?: number;
    height?: number;
    duration?: number;
    pages?: number;
  };
  uploadedAt: string;
  expiresAt?: string;
}

// 文件下载请求类型
export interface DownloadRequest {
  url: string;
  filename?: string;
  options?: {
    inline?: boolean;
    attachment?: boolean;
    expires?: string;
    token?: string;
  };
}

// 流式响应类型
export interface StreamResponse {
  id: string;
  event: string;
  data: any;
  timestamp: string;
  sequence?: number;
  retry?: number;
}

// WebSocket消息类型
export interface WebSocketMessage {
  id: string;
  type: string;
  event: string;
  data: any;
  timestamp: string;
  userId?: string;
  sessionId?: string;
  metadata?: Record<string, any>;
}

// 健康检查响应类型
export interface HealthCheckResponse {
  status: "healthy" | "degraded" | "unhealthy";
  version: string;
  uptime: number;
  timestamp: string;
  checks: Record<
    string,
    {
      status: "pass" | "fail" | "warn";
      responseTime?: number;
      message?: string;
      details?: any;
    }
  >;
  dependencies: Record<
    string,
    {
      status: "available" | "unavailable" | "degraded";
      responseTime?: number;
      version?: string;
      lastCheck: string;
    }
  >;
}

// 统计响应类型
export interface StatsResponse {
  period: {
    start: string;
    end: string;
    duration: string;
  };
  metrics: Record<
    string,
    {
      value: number;
      change?: number;
      changePercent?: number;
      trend?: "up" | "down" | "stable";
      unit?: string;
      format?: "number" | "percentage" | "currency" | "duration" | "bytes";
    }
  >;
  timeSeries?: Record<
    string,
    Array<{
      timestamp: string;
      value: number;
    }>
  >;
  breakdown?: Record<string, Record<string, number>>;
}

// 导出响应类型
export interface ExportResponse {
  id: string;
  status: "pending" | "processing" | "completed" | "failed";
  format: string;
  filename: string;
  size?: number;
  url?: string;
  expiresAt?: string;
  progress?: number;
  error?: string;
  createdAt: string;
  completedAt?: string;
  metadata?: {
    recordCount?: number;
    compressionRatio?: number;
    processingTime?: number;
  };
}

// 导入响应类型
export interface ImportResponse {
  id: string;
  status: "pending" | "processing" | "completed" | "failed" | "partial";
  filename: string;
  progress: number;
  summary: {
    total: number;
    processed: number;
    successful: number;
    failed: number;
    skipped: number;
  };
  errors?: Array<{
    row?: number;
    field?: string;
    message: string;
    data?: any;
  }>;
  warnings?: Array<{
    row?: number;
    field?: string;
    message: string;
    data?: any;
  }>;
  createdAt: string;
  completedAt?: string;
  metadata?: {
    fileSize: number;
    processingTime?: number;
    validationTime?: number;
  };
}

// 任务响应类型
export interface TaskResponse {
  id: string;
  type: string;
  status: "pending" | "running" | "completed" | "failed" | "cancelled";
  progress: number;
  result?: any;
  error?: ApiError;
  logs?: Array<{
    timestamp: string;
    level: "debug" | "info" | "warn" | "error";
    message: string;
    metadata?: Record<string, any>;
  }>;
  createdAt: string;
  startedAt?: string;
  completedAt?: string;
  estimatedDuration?: number;
  metadata?: {
    priority?: "low" | "normal" | "high" | "urgent";
    retryCount?: number;
    maxRetries?: number;
    dependencies?: string[];
  };
}

// 通知响应类型
export interface NotificationResponse {
  id: string;
  type: "info" | "success" | "warning" | "error";
  title: string;
  message: string;
  data?: any;
  read: boolean;
  persistent: boolean;
  expiresAt?: string;
  actions?: Array<{
    id: string;
    label: string;
    action: string;
    style?: "primary" | "secondary" | "danger";
    url?: string;
  }>;
  createdAt: string;
  readAt?: string;
  metadata?: {
    category?: string;
    priority?: "low" | "normal" | "high" | "urgent";
    source?: string;
    userId?: string;
    sessionId?: string;
  };
}

// 权限检查响应类型
export interface PermissionResponse {
  allowed: boolean;
  permissions: string[];
  restrictions?: Record<string, any>;
  reason?: string;
  metadata?: {
    userId?: string;
    roleId?: string;
    resourceId?: string;
    action?: string;
    context?: Record<string, any>;
  };
}

// 配额响应类型
export interface QuotaResponse {
  resource: string;
  used: number;
  limit: number;
  remaining: number;
  percentage: number;
  resetAt: string;
  resetInterval: "hour" | "day" | "week" | "month" | "year";
  exceeded: boolean;
  warnings?: Array<{
    threshold: number;
    message: string;
  }>;
  metadata?: {
    plan?: string;
    upgradeUrl?: string;
    contactSupport?: boolean;
  };
}

// 版本信息响应类型
export interface VersionResponse {
  version: string;
  buildNumber?: string;
  buildDate?: string;
  gitCommit?: string;
  gitBranch?: string;
  environment: "development" | "staging" | "production";
  features: string[];
  deprecations?: Array<{
    feature: string;
    deprecatedIn: string;
    removedIn?: string;
    replacement?: string;
    message: string;
  }>;
  changelog?: Array<{
    version: string;
    date: string;
    changes: Array<{
      type: "feature" | "bugfix" | "improvement" | "breaking";
      description: string;
    }>;
  }>;
}

// 缓存响应类型
export interface CacheResponse {
  hit: boolean;
  key: string;
  ttl?: number;
  size?: number;
  createdAt?: string;
  lastAccessed?: string;
  accessCount?: number;
  metadata?: {
    tags?: string[];
    dependencies?: string[];
    invalidationRules?: string[];
  };
}

// 限流响应类型
export interface RateLimitResponse {
  allowed: boolean;
  limit: number;
  remaining: number;
  resetAt: string;
  retryAfter?: number;
  window: string;
  policy: string;
  metadata?: {
    identifier?: string;
    endpoint?: string;
    method?: string;
    cost?: number;
  };
}

// HTTP状态码枚举
export enum HttpStatus {
  OK = 200,
  CREATED = 201,
  ACCEPTED = 202,
  NO_CONTENT = 204,
  BAD_REQUEST = 400,
  UNAUTHORIZED = 401,
  FORBIDDEN = 403,
  NOT_FOUND = 404,
  METHOD_NOT_ALLOWED = 405,
  CONFLICT = 409,
  UNPROCESSABLE_ENTITY = 422,
  TOO_MANY_REQUESTS = 429,
  INTERNAL_SERVER_ERROR = 500,
  BAD_GATEWAY = 502,
  SERVICE_UNAVAILABLE = 503,
  GATEWAY_TIMEOUT = 504,
}

// API错误码枚举
export enum ApiErrorCode {
  // 通用错误
  UNKNOWN_ERROR = "UNKNOWN_ERROR",
  INTERNAL_ERROR = "INTERNAL_ERROR",
  NETWORK_ERROR = "NETWORK_ERROR",
  TIMEOUT_ERROR = "TIMEOUT_ERROR",

  // 验证错误
  VALIDATION_ERROR = "VALIDATION_ERROR",
  INVALID_INPUT = "INVALID_INPUT",
  MISSING_REQUIRED_FIELD = "MISSING_REQUIRED_FIELD",
  INVALID_FORMAT = "INVALID_FORMAT",

  // 认证错误
  AUTHENTICATION_REQUIRED = "AUTHENTICATION_REQUIRED",
  INVALID_CREDENTIALS = "INVALID_CREDENTIALS",
  TOKEN_EXPIRED = "TOKEN_EXPIRED",
  TOKEN_INVALID = "TOKEN_INVALID",

  // 授权错误
  INSUFFICIENT_PERMISSIONS = "INSUFFICIENT_PERMISSIONS",
  ACCESS_DENIED = "ACCESS_DENIED",
  RESOURCE_FORBIDDEN = "RESOURCE_FORBIDDEN",

  // 资源错误
  RESOURCE_NOT_FOUND = "RESOURCE_NOT_FOUND",
  RESOURCE_ALREADY_EXISTS = "RESOURCE_ALREADY_EXISTS",
  RESOURCE_CONFLICT = "RESOURCE_CONFLICT",
  RESOURCE_LOCKED = "RESOURCE_LOCKED",

  // 限制错误
  RATE_LIMIT_EXCEEDED = "RATE_LIMIT_EXCEEDED",
  QUOTA_EXCEEDED = "QUOTA_EXCEEDED",
  FILE_TOO_LARGE = "FILE_TOO_LARGE",
  REQUEST_TOO_LARGE = "REQUEST_TOO_LARGE",

  // 服务错误
  SERVICE_UNAVAILABLE = "SERVICE_UNAVAILABLE",
  MAINTENANCE_MODE = "MAINTENANCE_MODE",
  DEPRECATED_ENDPOINT = "DEPRECATED_ENDPOINT",
  VERSION_NOT_SUPPORTED = "VERSION_NOT_SUPPORTED",
}

// 导出所有类型
export type {
  ApiResponse,
  ApiError,
  ResponseMeta,
  PaginationParams,
  PaginatedResponse,
  SearchParams,
  SearchResponse,
  BulkRequest,
  BulkResponse,
  UploadResponse,
  DownloadRequest,
  StreamResponse,
  WebSocketMessage,
  HealthCheckResponse,
  StatsResponse,
  ExportResponse,
  ImportResponse,
  TaskResponse,
  NotificationResponse,
  PermissionResponse,
  QuotaResponse,
  VersionResponse,
  CacheResponse,
  RateLimitResponse,
};
